package JZ57_二叉树的下一个结点;

class TreeLinkNode {
    int val;
    TreeLinkNode left = null;
    TreeLinkNode right = null;
    TreeLinkNode next = null;

    TreeLinkNode(int val) {
        this.val = val;
    }
}

public class Solution {
    public TreeLinkNode GetNext(TreeLinkNode pNode) {
        if (pNode.right != null){
            TreeLinkNode p = pNode.right;
            while (p.left != null){
                p = p.left;
            }
            return p;
        }

        if (pNode.next != null && pNode.next.left == pNode){
            return pNode.next;
        }

        if (pNode.next != null){
            while (pNode.next != null && pNode.next.right == pNode){
                pNode = pNode.next;
            }
            return pNode.next;
        }
        return null;

    }
}